package com.feinno.bug.actcache.service.impl;

import com.feinno.bug.actcache.entity.UserMSGVo;
import com.feinno.bug.actcache.mapper.UserMSGMapper;
import com.feinno.bug.actcache.service.MyRunner;
import com.feinno.bug.actcache.service.TaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zcy
 * @Description
 * @Date: 20:27 2018/11/2
 */
@Service("taskService")
public class TaskServiceImpl implements TaskService {

    private static final Logger logger = LoggerFactory.getLogger(TaskServiceImpl.class);

    private static volatile ExecutorService executorService;

    @Autowired
    private UserMSGMapper mapper;

    static {
        executorService = new ThreadPoolExecutor(30, 50,
                0L, TimeUnit.SECONDS,
                // 该配置的策略：能够减缓新任务的提交速度
                new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());
    }

    private static final String DIC_KEY = "OSS:RES:PHONE:";
    private static final String DIC_KEY_GROUP = "OSS:RES:PHONEGROUP:";

    @Override
    public void mytask(int x) throws InterruptedException {
        List<UserMSGVo> list = mapper.getmax(x);
        logger.info("max siez is {}", list.size());
        for (int i = 0; i < list.size(); i++) {
            UserMSGVo userMSGVo = list.get(i);
            executorService.submit(new MyRunner(DIC_KEY, i, userMSGVo.getPhone(), userMSGVo.getGroup_id()));
        }
        List<UserMSGVo> list1 = mapper.getmin(x);
        logger.info("min siez is {}", list1.size());
        for (int i = 0; i < list1.size(); i++) {
            UserMSGVo userMSGVo = list1.get(i);
            executorService.submit(new MyRunner(DIC_KEY_GROUP, i, userMSGVo.getPhone(), userMSGVo.getGroup_id()));
        }
//        executorService.shutdown();
//        while (true) {
//            if (executorService.isTerminated()) {
//                logger.info("所有的子线程都结束了！");
//                break;
//            }
//            Thread.sleep(1000);
//        }
//        final long end = System.currentTimeMillis();
//        logger.info("一共耗时 {} s",(end - start) / 1000);
    }
}
